package com.huaxin.hxcloud.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.SignInfoDTO;
import com.huaxin.common.Global;
import com.huaxin.common.media.Util;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxin.common.view.avatarimageview.HxAvatarImageGlide;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.work.HxSignDesActivity;
import com.huaxin.hxcloud.work.HxSignEditActivity;
import com.huaxin.hxcloud.work.event.HxIsRefreshEventBus;

import net.qiujuer.genius.ui.widget.ImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/11/8.
 *
 * @desc * 考勤 -- 签到
 */

public class SignFragment extends BaseFragment {


    final static int UPDATE_TIME = 0;
    final static int UPDATE_LOC  = 1;
    @BindView(R.id.toolbar)
    Toolbar                  toolbar;
    @BindView(R.id.time)
    TextView                 time;
    @BindView(R.id.date)
    TextView                 date;
    @BindView(R.id.tv_station)
    TextView                 tvStation;
    @BindView(R.id.sign)
    ImageView                signImg;
    @BindView(R.id.headPortrait_view)
    AvatarImageView          headPortraitView;
    @BindView(R.id.user_name)
    TextView                 userName;
    @BindView(R.id.company)
    TextView                 company;
    @BindView(R.id.signin_time)
    TextView                 signinTime;
    @BindView(R.id.signin_address) //签到
    TextView                 signinAddress;
    @BindView(R.id.signback_time)
    TextView                 signbackTime;
    @BindView(R.id.signback_address)//签退
    TextView                 signbackAddress;
    @BindView(R.id.rl_bottom)
    RelativeLayout           rlBottom;
    @BindView(R.id.stateimg)
    android.widget.ImageView mStateimg;
    @BindView(R.id.signin_img)
    android.widget.ImageView mSigninImg;
    @BindView(R.id.signback_img)
    android.widget.ImageView mSignbackImg;
    @BindView(R.id.content)
    RelativeLayout content;

    private int INTENT_EDIT = 0; //跳转编辑
    private int INTENT_EDS  = 1; //跳转描述

    public static int TYPE_SIGN_IN  = 0; //签到标识 后台协商的
    public static int TYPE_SIGN_OUT = 1; //签退标识

    private SignInfoDTO mSignInfo;
    private static final String  TAG      = "SignFragment";
    @SuppressLint("HandlerLeak")
    private              Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_TIME:
                    long sysTime = System.currentTimeMillis();
                    loadText(time, dateFormat(sysTime, "hh:mm"));
                    loadText(date, dateFormat(sysTime, "EEEE yyyy-MM-dd"));
                    sendEmptyMessageDelayed(UPDATE_TIME, 1000);
                    break;
                case UPDATE_LOC:
                default:
                    break;

            }
        }
    };
    private PopupWindow topTipPop;
    private android.widget.ImageView iv_state;
    private TextView tv_stata;
    private TextView tv_sign_time;
    private TextView tv_know;

    @Override
    protected void updateLoadStatus(int status) {
        super.updateLoadStatus(status);
        switch (status) {
            case LOADING:
                rlBottom.setVisibility(View.INVISIBLE);
                break;
            case LOAD_SUCCESS:
                rlBottom.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }


    @Override
    protected int getContentViewId() {
        return R.layout.fragment_sign;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public int getLoadFrameId() {
        return R.id.content;
    }


    @Override
    protected void requestData() {
        ApiRequestData(LOADING);
    }


    private void updateView() {
        if (Global.user != null) {

            HxAvatarImageGlide instance = HxAvatarImageGlide.getInstance();
            instance.setHeadImage(getContext(), Global.user.getImgUrl(), Global.user.getNickName(), headPortraitView);
            // loadImg(headPortrait, Global.user.getImgUrl(), R.drawable.head_portrait);
            loadText(userName, Global.user.getNickName());
            loadText(company, Global.user.getOrgName());
        }
        if (mSignInfo != null) {
            loadText(tvStation, mSignInfo.getStationName(), mSignInfo.getAddress());

            if(mSignInfo.getInDate()==0){
                signinTime.setText("签到时间：未签到");
                mSigninImg.setVisibility(View.GONE);
            }else{
                signinTime.setText("签到时间："+dateFormat(mSignInfo.getInDate(), "HH:mm"));
                mStateimg.setImageResource(R.drawable.icon_sign_state_2);
                mSigninImg.setVisibility(View.VISIBLE);
            }

            if(mSignInfo.getBackDate()==0){
                signbackTime.setText("签退时间：未签退");
                mSignbackImg.setVisibility(View.GONE);
            }else{
                signbackTime.setText("签退时间："+dateFormat(mSignInfo.getBackDate(), "HH:mm"));
                mStateimg.setImageResource(R.drawable.icon_sign_state_3);
                mSignbackImg.setVisibility(View.VISIBLE);
            }
            loadText(signinAddress, mSignInfo.getInAddress());
            loadText(signbackAddress, mSignInfo.getBackAddress());

            // 0 签到 1签退 2更新签退 3 无签到站点
            switch (mSignInfo.getSignState()) {
                case 0:
                    toolbar.setTitle("签到");
                    signImg.setImageResource(R.drawable.icon_sign_in);
                    break;
                case 1:
                    toolbar.setTitle("签退");
                    signImg.setImageResource(R.drawable.icon_sign_back);
                    break;
                case 2:
                    //更新签退
                    toolbar.setTitle("签退");
                    signImg.setImageResource(R.drawable.icon_sign_back);
                    break;
            }
        }

    }


    private void ApiAddSign() {
        LatLng latLng = BaseApp.getLatLng();
        final Dialog waitDialog = DialogUtil.getWaitDialog(getContext(), "提交中...");
        waitDialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().addSign(null, new Date().getTime(),
                mSignInfo.getStationCode(), latLng.longitude, latLng.latitude, null, null);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                BaseDTO baseDTO = response.body();
                if (baseDTO !=null && baseDTO.isSuccessful()) {
                    signSuccess("打卡成功", true,waitDialog,null);
                    if (mSignInfo.getSignState()==0){
                        //签到成功
                        mSignInfo.setSignState(1);
                        signinTime.setText("签到时间："+dateFormat(System.currentTimeMillis(), "HH:mm"));
                        toolbar.setTitle("签退");
                        signImg.setImageResource(R.drawable.icon_sign_back);
                        mStateimg.setImageResource(R.drawable.icon_sign_state_2);
                        mSigninImg.setVisibility(View.VISIBLE);
                        loadText(signinAddress,BaseApp.getAddrStr());

                    }else if (mSignInfo.getSignState()==1){
                        //签退
                        signbackTime.setText("签退时间："+dateFormat(System.currentTimeMillis(), "HH:mm"));
                        mStateimg.setImageResource(R.drawable.icon_sign_state_3);
                        mSignbackImg.setVisibility(View.VISIBLE);
                        loadText(signbackAddress,BaseApp.getAddrStr());

                    }else if (mSignInfo.getSignState() == 2){
                        //更新签退
                        signbackTime.setText("签退时间："+dateFormat(System.currentTimeMillis(), "HH:mm"));
                        loadText(signbackAddress,BaseApp.getAddrStr());

                    }
                } else {
                    signSuccess("打卡失败", false,waitDialog,"数据异常");
                }
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                waitDialog.dismiss();
                signSuccess("打卡失败", false, waitDialog,"网络故障");
            }
        });
    }

    /**
     * 打卡提示
     * @param des
     * @param isSuccess
     * @param waitDialog
     */
    private void signSuccess(String des, boolean isSuccess, Dialog waitDialog,String detail) {
        //  View parent = ((ViewGroup) findViewById(R.id.content)).getChildAt(0);
        if (topTipPop ==null){
            View popView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_sign_toptip, null);
            topTipPop = new PopupWindow(popView, Util.getScreenWidth(getActivity())-80, ViewGroup.LayoutParams.WRAP_CONTENT);
            iv_state= (android.widget.ImageView) popView.findViewById(R.id.iv_sign_state);
            tv_stata= (TextView) popView.findViewById(R.id.tv_state);
            tv_sign_time= (TextView) popView.findViewById(R.id.tv_signin_time);
            tv_know= (TextView) popView.findViewById(R.id.tv_know);
        }
        topTipPop.setAnimationStyle(R.style.AnimationFade);
        if (topTipPop !=null && !topTipPop.isShowing()){
            // topTipPop.showAtLocation(content, Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
            if (toolbar == null){
                //防止接口请求超时，activity已销毁弹出
                return;
            }
            topTipPop.showAsDropDown(toolbar,40,0,Gravity.CENTER_HORIZONTAL);
        }
        if (waitDialog != null){
            waitDialog.dismiss();
        }
        tv_stata.setText(des);
        if (isSuccess){
            iv_state.setImageResource(R.drawable.icon_checkbox_circle_checked);
        }else {
            iv_state.setImageResource(R.drawable.icon_error);
        }
        if (detail != null){
            tv_sign_time.setText(detail);
        }else{
            tv_sign_time.setText("打卡时间："+dateFormat2(System.currentTimeMillis()));
        }
        tv_know.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (topTipPop.isShowing()){
                    topTipPop.dismiss();
                }
            }
        });
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (topTipPop != null && topTipPop.isShowing()){
                    topTipPop.dismiss();
                }
            }
        },3000);
    }


    /**
     * @desc 获取 签到信息
     * @author songxf
     * created at 2017/7/19 14:37
     */
    private void ApiRequestData(int status) {
        updateLoadStatus(status);
        LatLng latLng = BaseApp.getLatLng();
        if (latLng == null){
            return;
        }
        Call<SignInfoDTO> call = HxTransmitRequestHelper.getRequestApi().getSignInfo(latLng.longitude, latLng.latitude);
        Log.d(TAG, "ApiRequestData: ---->" + call.request().url());
        autoClose(call);
        call.enqueue(new Callback<SignInfoDTO>() {
            @Override
            public void onResponse(Call<SignInfoDTO> call, Response<SignInfoDTO> response) {
                SignInfoDTO signInfo = response.body();
                //  Log.d(TAG, "onResponse: " + response.body().toString());
                if (response.isSuccessful()) {
                    if (signInfo != null && signInfo.isSuccessful()) {
                        updateLoadStatus(LOAD_SUCCESS);
                        mSignInfo = signInfo;
                        updateView();

                    } else {
                        updateLoadStatus(LOAD_SUCCESS);
                        mSignInfo = signInfo;
                        updateView();
                        //updateLoadStatus(LOAD_ERROR);
                    }
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<SignInfoDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
                Log.d(TAG, "onFailure:11--> " + t);
            }
        });

    }

    @OnClick({R.id.sign, R.id.signin_img, R.id.signback_img})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.sign://签到按钮
                if (mSignInfo == null || mSignInfo.getStationCode() == null) {
                    signSuccess("打卡失败", false,null,"附近无站点！");
                    return;
                }
                if (mSignInfo.getSignState()==2){
                    //提示是否更新签退时间
                    AlertDialog.Builder dialog = DialogUtil.getDialog(getActivity());
                    dialog.setMessage("当前已存在签退记录，是否更新签退？");
                    dialog.setTitle("更新签退？");
                    dialog.setPositiveButton("更新", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ApiAddSign();
                        }
                    });
                    dialog.setNegativeButton("取消", null);
                    dialog.show();
                }else{
                    ApiAddSign();
                }
                break;
            case R.id.signin_img://签到描述
                if (TextUtils.isEmpty(mSignInfo.getInDes())) {
                    //ToastUtil.showToast("签到描述");
                    intentSignEditOrDesActivity(INTENT_EDS, TYPE_SIGN_IN, mSignInfo);

                } else {
                    intentSignEditOrDesActivity(INTENT_EDIT, TYPE_SIGN_IN, mSignInfo);
                    // ToastUtil.showToast("签到编辑");
                }

                break;
            case R.id.signback_img://签退描述
                if (TextUtils.isEmpty(mSignInfo.getBackDes())) {
                    //ToastUtil.showToast("签退描述");
                    intentSignEditOrDesActivity(INTENT_EDS, TYPE_SIGN_OUT, mSignInfo);
                } else {
                    // ToastUtil.showToast("签退编辑");
                    intentSignEditOrDesActivity(INTENT_EDIT, TYPE_SIGN_OUT, mSignInfo);
                }
                break;
        }
    }


    /**
     * 跳转是编辑还是描述 Activity
     *
     * @param editOrDes
     * @param type
     */
    private void intentSignEditOrDesActivity(int editOrDes, int type, SignInfoDTO signInfo) {
        Intent intent = null;
        List<SignInfoDTO.SignTypesBean> signTypesList = signInfo.getSignTypes();
        if (INTENT_EDIT == editOrDes) {//编辑
            Bundle bundle = new Bundle();
            bundle.putParcelable("SIGN_INFO_DTO", signInfo);
            intent = new Intent(getActivity(), HxSignEditActivity.class);
            intent.putExtras(bundle);

        } else if (INTENT_EDS == editOrDes) {  //描述
            intent = new Intent(getActivity(), HxSignDesActivity.class);
        }
        intent.putExtra("TYPE", type);
        intent.putParcelableArrayListExtra("SIGN_TYPES", (ArrayList<? extends Parcelable>) signTypesList);
        intent.putExtra("SIGN_ID", signInfo.getSignId());
        startActivity(intent);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void isRefreshEvent(HxIsRefreshEventBus message) {
        if (message.isRefresh) {
            ApiRequestData(LOAD_SUCCESS);
        }
    }

    @Override
    public void onDestroyView() {
        mHandler.removeMessages(UPDATE_TIME);
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        if (topTipPop != null && topTipPop.isShowing()){
            topTipPop.dismiss();
        }
    }

    @Override
    protected void onResumeView() {
        super.onResumeView();
        ((BaseActivity) getActivity()).setSupportActionBar(toolbar);
        updateView();
        mHandler.sendEmptyMessage(UPDATE_TIME);
    }


}
